import os
import sys
from typing import List, Dict, Any, Optional

# Add project root directory to system path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, ".."))
sys.path.append(project_root)

from User.BaseUser import BaseUser


class Teacher(BaseUser):
    """Teacher class, inherits from BaseUser"""
    
    def __init__(self, ID: str, Password: str, ChineseName: str, EnglishName: str, Courses: Optional[List] = None):
        """Initialize teacher information"""
        super().__init__(ID, Password, "Teacher")  # Parent class parameter name changed to lowercase 'role'
        self.ChineseName = ChineseName
        self.EnglishName = EnglishName
        self.Courses = Courses if Courses is not None else []  # List of taught courses
    
    def view_dashboard(self) -> str:
        """View teacher dashboard"""
        course_info = "\n".join([f"- {course.CourseName} ({course.ID})" for course in self.Courses])
        
        return (f"=== Teacher Dashboard ===\n"
                f"ID: {self.ID}\n"
                f"Name: {self.ChineseName} ({self.EnglishName})\n"
                f"Taught Courses ({len(self.Courses)}):\n{course_info}")
    
    def create_course(self, course_id: str, course_name: str, course_time: str, classroom: str) -> bool:
        """Create a new course"""
        from Course.Course import Course
        
        # Check if course ID already exists
        if any(c.ID == course_id for c in self.Courses):
            return False
            
        # Create new course
        new_course = Course(
            ID=course_id,
            Teacher=self,
            CourseName=course_name,
            CourseTime=course_time,
            Classroom=classroom
        )
        
        self.Courses.append(new_course)
        return True
    
    def delete_course(self, course_id: str) -> bool:
        """Delete a course"""
        from Course.Course import Course
        
        for course in self.Courses:
            if course.ID == course_id:
                self.Courses.remove(course)
                return True
                
        return False
    
    def create_assignment(self, title: str, description: str, deadline: str, course_id: str) -> bool:
        """Create a new assignment"""
        from Course.Course import Course
        from Assignment.Assignment import Assignment
        from datetime import datetime
        
        # Find the course
        course = next((c for c in self.Courses if c.ID == course_id), None)
        if not course:
            return False
            
        # Create assignment
        assignment_id = f"{course_id}_A{len(course.Assignments) + 1}"
        
        try:
            deadline_dt = datetime.strptime(deadline, "%Y-%m-%d %H:%M")
        except ValueError:
            return False
            
        new_assignment = Assignment(
            ID=assignment_id,
            Title=title,
            Description=description,
            Deadline=deadline_dt,
            Course=course
        )
        
        course.add_assignment(new_assignment)
        return True
    
    def grade_assignment(self, course_id: str, assignment_id: str, student_id: str, grade: float, feedback: str) -> bool:
        """Grade an assignment"""
        from Course.Course import Course
        from User.Student import Student
        
        # Find the course
        course = next((c for c in self.Courses if c.ID == course_id), None)
        if not course:
            return False
            
        # Find the assignment
        assignment = course.get_assignment_by_id(assignment_id)
        if not assignment:
            return False
            
        # Find the student
        student = next((s for s in course.Students if s.ID == student_id), None)
        if not student:
            return False
            
        # Grade the submission
        return assignment.grade_submission(student, grade, feedback, self.ID)
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for persistence"""
        base_dict = super().to_dict()
        return {
            **base_dict,
            "chinese_name": self.ChineseName,
            "english_name": self.EnglishName,
            "courses": [course.ID for course in self.Courses]
        }